import type { Next, Context } from 'koa';
import knex from '../utils/knex';

/**
 * @api {get} /config/retrieve 查询参数设置
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName retrieve
 * @apiGroup 参数设置
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     name       参数名称【非必填】
 * @apiParam {String}     is_sys     是否系统内置 0:否 1:是【非必填】
 * @apiParam {String}     key        参数键值【非必填】
 * @apiParam {String}     startTime  参数创建时间-开始【非必填】
 * @apiParam {String}     endTime    参数创建时间-结束【非必填】
 * @apiParam {String}     status     参数状态 (0:正常 1:停用)【非必填】
 *
 * @apiUse RequestHeader
 * @apiUse configRetrieveSuccess
 * @apiUse RequestError
 */
async function retrieveAction(ctx: Context, next: Next) {
    const { page = 1, size = 10, name = '', key = '', is_sys: isSys = '', status = '', startTime = '', endTime = '' } = ctx.query;
    const whereObj: Record<string, any> = {};
    if (name) {
        whereObj.name = ['like', `%${name}%`];
    }
    if (key) {
        whereObj.key = key;
    }
    if (isSys) {
        whereObj.is_sys = isSys;
    }
    if (status) {
        whereObj.status = status;
    }
    if (startTime && endTime) {
        whereObj.create_time = ['between', startTime, endTime];
    }
    try {
        const data = await knex('sys_config')
            .where(whereObj)
            .offset(((page as number) - 1) * (size as number))
            .limit(size as number)
            .select();
        const [count] = await knex('sys_config').where(whereObj).count();
        ctx.success(
            {
                data,
                count: Object.values(count)[0],
            },
            '查询成功',
        );
    } catch (e: any) {
        ctx.fail(500, e.toString());
    }
    return next();
}

/**
 * @api {post} /config/add 新增参数配置
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName add
 * @apiGroup 参数设置
 *
 * @apiParam {String}  name       参数名称【必填】
 * @apiParam {String}  key        参数键名【必填】
 * @apiParam {String}  value      参数键值【必填】
 * @apiParam {String}  is_sys     是否系统内置 0:否 1:是【必填】
 * @apiParam {String}  remark     备注【必填】
 * @apiParam {String}  status     参数状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse addSuccess
 * @apiUse RequestError
 */
async function addAction(ctx: Context, next: Next) {
    const { name = '', key = '', value = '', is_sys: isSys = '', status, remark = '' } = ctx.request.body;
    try {
        await knex('sys_config').insert({
            name: name,
            key: key,
            value: value,
            is_sys: isSys,
            status: status,
            remark: remark,
        });
        ctx.success('', '新增成功');
    } catch (e) {
        ctx.fail(500, '新增失败  ' + e);
    }
    return next();
}

/**
 * @api {delete} /config/delete 删除参数
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName delete
 * @apiGroup 参数设置
 *
 * @apiParam {int}     id      参数id【必填】
 * @apiParam {String}  is_sys  是否系统内置 0:否 1:是【必填】
 *
 * @apiUse RequestHeader
 * @apiUse deleteSuccess
 * @apiUse RequestError
 */
async function deleteAction(ctx: Context, next: Next) {
    const { id, is_sys: isSys = '' } = ctx.request.body;
    try {
        if (isSys === '1') {
            ctx.fail(400, '系统内置参数不允许删除');
            return next();
        }
        await knex('sys_config').where({ id: id }).delete();
        ctx.success('', '删除成功');
    } catch (e) {
        ctx.fail(500, '删除失败  ' + e);
    }
    return next();
}

/**
 * @api {put} /config/update 修改参数配置
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen
 * @apiName update
 * @apiGroup 参数设置
 *
 * @apiParam {int}     id         参数id【必填】
 * @apiParam {String}  name       参数名称【必填】
 * @apiParam {String}  key        参数键名【必填】
 * @apiParam {String}  value      参数键值【必填】
 * @apiParam {String}  is_sys     是否系统内置 0:否 1:是【必填】
 * @apiParam {String}  remark     备注【必填】
 * @apiParam {String}  status     参数状态 (0:正常 1:停用)【必填】
 *
 * @apiUse RequestHeader
 * @apiUse updateSuccess
 * @apiUse RequestError
 */
async function updateAction(ctx: Context, next: Next) {
    const { id, name = '', key = '', value = '', is_sys: isSys = '', status, remark = '' } = ctx.request.body;
    try {
        await knex('sys_config').where('id', id).update({
            name: name,
            key: key,
            value: value,
            is_sys: isSys,
            status: status,
            remark: remark,
        });
        ctx.success('', '修改成功');
    } catch (e) {
        ctx.fail(500, '修改失败  ' + e);
    }
    return next();
}

/**
 * @api {get} /config/info 获取参数配置详情
 * @apiVersion 1.0.0
 * @apiDescription create by wuyanshen -> 全局获取配置
 * @apiName info
 * @apiGroup 参数设置
 *
 * @apiUse RequestPagingParam
 * @apiParam {String}     key        参数键值【非必填】
 *
 * @apiUse RequestHeader
 * @apiUse configInfoSuccess
 * @apiUse RequestError
 */
async function infoAction(ctx: Context, next: Next) {
    const { key = '' } = ctx.query;
    try {
        const res = await knex('sys_config').where({ key: key }).first();
        ctx.success(res, '查询成功');
    } catch (e) {
        ctx.fail(500, '查询失败  ' + e);
    }
    return next();
}

const configController = {
    retrieveAction,
    addAction,
    deleteAction,
    updateAction,
    infoAction,
};

export default configController;
